package com.teemor.auth.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teemor.auth.bean.po.Resource;
import com.teemor.auth.bean.po.ResourceRole;
import com.teemor.auth.service.ResourceRoleService;
import com.teemor.auth.service.ResourceService;
import com.teemor.common.bean.utils.BeanConvertor;
import com.teemor.common.bean.utils.enums.DataStatus;
import com.teemor.open.openauth.AuthUtils;
import com.teemor.open.openauth.model.AuthResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ename zhoulk
 * @cname 周李科
 * @date 2020/6/3 10:07
 */
@Component
public class LoadResoureSchedule {

    @Autowired
    private ResourceRoleService resourceRoleService;
    @Autowired
    private ResourceService resourceService;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void run() {
        List<Resource> resourceList = resourceService.list(new QueryWrapper<Resource>()
                .eq("status", DataStatus.USE.value()));
        if (CollectionUtils.isEmpty(resourceList)) {
            AuthUtils.cleanResource();
            return;
        }
        List<Integer> resourceIds = resourceList.stream().map(Resource::getId).collect(Collectors.toList());
        List<ResourceRole> resourceRoleList = resourceRoleService.list(new QueryWrapper<ResourceRole>()
                .eq("status", DataStatus.USE.value())
                .in("resource_id", resourceIds));
        Map<Integer, List<ResourceRole>> resourceRoleMap = resourceRoleList.stream()
                .collect(Collectors.groupingBy(ResourceRole::getResourceId));
        List<AuthResource> authResources = new ArrayList<>();
        resourceList.forEach(resource -> {
            AuthResource authResource = BeanConvertor.convertBean(resource, AuthResource.class);
            List<ResourceRole> roles = resourceRoleMap.get(resource.getId());
            List<Integer> roleIds = roles.stream().map(ResourceRole::getRoleId).collect(Collectors.toList());
            authResource.setRoles(roleIds);
            authResources.add(authResource);
        });
        if (authResources.size() > 0)
            AuthUtils.cacheResource(authResources);
    }
}
